//
//  ViewController.m
//  GPUImage_MyDemo
//
//  Created by yuedongkui on 2018/5/16.
//  Copyright © 2018年 LY. All rights reserved.
//

#import "ViewController.h"
#import "GPUImage.h"
#import "UIImage+Common.h"
#import "BottomBarView.h"
#import "EnhanceBarView.h"
#import "FilterBarView.h"
#import "CameraViewController.h"

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, BottomBarViewDelegate, EnhanceBarViewDelegate, FilterBarViewDelegate>

@property (nonatomic, strong) UIImageView *currentImageView;

@property (nonatomic, strong) BottomBarView *bottomBar;
@property (nonatomic, strong) EnhanceBarView *enhanceBar;//增强工具条
@property (nonatomic, strong) FilterBarView *filterBar;//滤镜工具条

@property (nonatomic, strong) NSMutableArray *storedImages;//需要撤销的图片
@property (nonatomic, strong) UIImage *origalImage;//原始图片

@property (nonatomic, strong) GPUImageFilter *currentFilter;
@property (nonatomic, assign) EnhanceFilterType enhanceFilterType;



@end




@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;

    //
    self.currentImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.currentImageView.backgroundColor = [UIColor redColor];
    self.currentImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.currentImageView];
    
    //
    UIButton *cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cameraButton setTitle:@"相机" forState:UIControlStateNormal];
    [cameraButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cameraButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:cameraButton];
    [cameraButton addTarget:self action:@selector(cameraButtonTap:) forControlEvents:UIControlEventTouchUpInside];
    [cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.view).offset(28);
        make.size.mas_offset(CGSizeMake(64, 40));
    }];
    
    UIButton *photoLibraryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [photoLibraryButton setTitle:@"相册" forState:UIControlStateNormal];
    [photoLibraryButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [photoLibraryButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:photoLibraryButton];
    [photoLibraryButton addTarget:self action:@selector(photoLibraryButtonTap:) forControlEvents:UIControlEventTouchUpInside];
    [photoLibraryButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20);
        make.top.equalTo(cameraButton);
        make.size.equalTo(cameraButton);
    }];
    
    UIButton *undoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [undoButton setTitle:@"撤销" forState:UIControlStateNormal];
    [undoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [undoButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:undoButton];
    [undoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_centerX).offset(-10);
        make.top.bottom.equalTo(photoLibraryButton);
    }];
    
    UIButton *redoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [redoButton setTitle:@"恢复" forState:UIControlStateNormal];
    [redoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [redoButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:redoButton];
    [redoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_centerX).offset(10);
        make.top.bottom.equalTo(photoLibraryButton);
    }];
    
    //
    self.bottomBar = [[BottomBarView alloc] initWithFrame:CGRectZero];
    self.bottomBar.backgroundColor = [UIColor greenColor];
    self.bottomBar.delegate = self;
    [self.view addSubview:self.bottomBar];
    [self.bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).offset(0);
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-kBarHeight);
        } else {
            make.top.equalTo(self.view.mas_bottom).offset(-kBarHeight);
        }
        make.bottom.equalTo(self.view).offset(0);
    }];
    
    [self.currentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.bottom.equalTo(self.bottomBar.mas_top).offset(0);
    }];
    
    //增强
    self.enhanceBar = [[EnhanceBarView alloc] initWithFrame:CGRectZero];
    self.enhanceBar.delegate = self;
    [self.view addSubview:self.enhanceBar];
    [self.enhanceBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).offset(0);
        make.top.equalTo(self.view.mas_bottom).offset(0);
        make.bottom.equalTo(self.view).offset(kBarHeight);
    }];
    [self enhanceBarView:self.enhanceBar didSelectRow:0];//选中第一行
    
    //滤镜
    self.filterBar = [[FilterBarView alloc] initWithFrame:CGRectZero];
    self.filterBar.delegate = self;
    [self.view addSubview:self.filterBar];
    [self.filterBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).offset(0);
        make.top.equalTo(self.view.mas_bottom).offset(0);
        make.bottom.equalTo(self.view).offset(kBarHeight);
    }];
}

#pragma mark - Button Events
- (void)cameraButtonTap:(id)sender
{
    CameraViewController *vc = [[CameraViewController alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
    
    [vc captureImageCallback:^(UIImage *processedImage, NSError *error) {
        self.origalImage = processedImage;
        self.currentImageView.image = processedImage;
    }];
}

- (void)photoLibraryButtonTap:(id)sender
{
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^
     {
         UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
         self.origalImage = [image fixOrientation];
         self.currentImageView.image = self.origalImage;

         
//         NSString *path = [[LYSandBoxUtils cache] stringByAppendingPathComponent:kWallPaperBigImageName];
//         NSData *photoData = UIImagePNGRepresentation(image);
//         [photoData writeToFile:path atomically:NO];
     }];
}

#pragma mark - BottomBarViewDelegate
- (void)bottomBarView:(id)bottomBar didSelectRow:(NSInteger)row
{
    if (row == 0) {//增强
        [UIView animateWithDuration:0.25 delay:0 options:0 animations:^{
            [self.enhanceBar mas_updateConstraints:^(MASConstraintMaker *make) {
                if (@available(iOS 11.0, *)) {
                    make.top.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-kBarHeight);
                } else {
                    make.top.equalTo(self.view.mas_bottom).offset(-kBarHeight);
                }
            }];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }
    else if (row == 1) {//滤镜
        [UIView animateWithDuration:0.25 delay:0 options:0 animations:^{
            [self.filterBar mas_updateConstraints:^(MASConstraintMaker *make) {
                if (@available(iOS 11.0, *)) {
                    make.top.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-kBarHeight);
                } else {
                    make.top.equalTo(self.view.mas_bottom).offset(-kBarHeight);
                }
            }];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }
}

#pragma mark - EnhanceBarViewDelegate
- (void)enhanceBarDidBack:(EnhanceBarView *)enhanceBarView
{
    [UIView animateWithDuration:0.25 animations:^{
        [self.enhanceBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view).offset(0);
            make.top.equalTo(self.view.mas_bottom).offset(0);
            make.bottom.equalTo(self.view).offset(kBarHeight);
        }];
        [self.view layoutIfNeeded];
    }];
}

- (void)enhanceBarView:(EnhanceBarView *)bar didSelectRow:(NSInteger)row
{
    self.enhanceFilterType = row + 1;
    switch (self.enhanceFilterType) {
        case EnhanceFilterTypeBrightness: {//亮度
            self.currentFilter = [[GPUImageBrightnessFilter alloc] init];
            [bar configMinValue:-1 maxValue:1 defaultValue:0];
        } break;
        case EnhanceFilterTypeExposure: {//曝光
            self.currentFilter = [[GPUImageExposureFilter alloc] init];
            [bar configMinValue:-10 maxValue:10 defaultValue:0];
        } break;
        case EnhanceFilterTypeContrast: {//对比度
            self.currentFilter = [[GPUImageContrastFilter alloc] init];
            [bar configMinValue:0 maxValue:4 defaultValue:1];
        } break;
        case EnhanceFilterTypeSaturation: {//饱和度
            self.currentFilter = [[GPUImageSaturationFilter alloc] init];
            [bar configMinValue:0 maxValue:2 defaultValue:1];
        } break;
        case EnhanceFilterTypeGamma: {//伽马值
            self.currentFilter = [[GPUImageGammaFilter alloc] init];
            [bar configMinValue:0 maxValue:3 defaultValue:1];
        } break;
//        case EnhanceFilterTypeLevel: {//色阶
//            ((GPUImageLevelsFilter *)self.currentFilter). = value;
//        } break;
        case EnhanceFilterTypeHue: {//色相
            self.currentFilter = [[GPUImageHueFilter alloc] init];
            [bar configMinValue:-180 maxValue:180 defaultValue:90];
        } break;
//        case EnhanceFilterTypeVibrance: {//自然饱和度
//            ((GPUImageVibranceFilter *)self.currentFilter).vibrance = value;
//        } break;
        case EnhanceFilterTypeWhiteBalance: {//白平衡
            self.currentFilter = [[GPUImageWhiteBalanceFilter alloc] init];
            [bar configMinValue:4000 maxValue:7000 defaultValue:5000];
        } break;
        case EnhanceFilterTypeShadow: {//阴影
            self.currentFilter = [[GPUImageHighlightShadowFilter alloc] init];
            [bar configMinValue:0 maxValue:1 defaultValue:0];
        } break;
        case EnhanceFilterTypeHighligh: {//高光
            self.currentFilter = [[GPUImageHighlightShadowFilter alloc] init];
            [bar configMinValue:1 maxValue:0 defaultValue:0];
        } break;
//        case EnhanceFilterTypeSkinTone: {//肤色
//            ((GPUImageSkinToneFilter *)self.currentFilter). = value;
//        } break;
        default: break;
    }
}

- (void)enhanceBarView:(EnhanceBarView *)bar didChangeValue:(CGFloat)value
{
    switch (self.enhanceFilterType) {
        case EnhanceFilterTypeBrightness: {//亮度
                ((GPUImageBrightnessFilter *)self.currentFilter).brightness = value;
            } break;
        case EnhanceFilterTypeExposure: {//曝光
            ((GPUImageExposureFilter *)self.currentFilter).exposure = value;
        } break;
        case EnhanceFilterTypeContrast: {//对比度
            ((GPUImageContrastFilter *)self.currentFilter).contrast = value;
        } break;
        case EnhanceFilterTypeSaturation: {//饱和度
            ((GPUImageSaturationFilter *)self.currentFilter).saturation = value;
        } break;
        case EnhanceFilterTypeGamma: {//伽马值
            ((GPUImageGammaFilter *)self.currentFilter).gamma = value;
        } break;
        case EnhanceFilterTypeLevel: {//色阶
//            ((GPUImageLevelsFilter *)self.currentFilter). = value;
        } break;
        case EnhanceFilterTypeHue: {//色相
            ((GPUImageHueFilter *)self.currentFilter).hue = value;
        } break;
//        case EnhanceFilterTypeVibrance: {//自然饱和度
//            ((GPUImageVibranceFilter *)self.currentFilter).vibrance = value;
//        } break;
        case EnhanceFilterTypeWhiteBalance: {//白平衡
            ((GPUImageWhiteBalanceFilter *)self.currentFilter).temperature = value;
        } break;
        case EnhanceFilterTypeShadow: {//阴影
            ((GPUImageHighlightShadowFilter *)self.currentFilter).shadows = value;
        } break;
        case EnhanceFilterTypeHighligh: {//高光
            ((GPUImageHighlightShadowFilter *)self.currentFilter).highlights = value;
        } break;
//        case EnhanceFilterTypeSkinTone: {//肤色
//            ((GPUImageSkinToneFilter *)self.currentFilter). = value;
//        } break;
        default: break;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = [self.currentFilter imageByFilteringImage:self.origalImage];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.currentImageView.image = image;
        });
    });
}

#pragma mark - FilterBarViewDelegate
- (void)filterBarDidBack:(FilterBarView *)filterBarView
{
    [UIView animateWithDuration:0.25 animations:^{
        [self.filterBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view).offset(0);
            make.top.equalTo(self.view.mas_bottom).offset(0);
            make.bottom.equalTo(self.view).offset(kBarHeight);
        }];
        [self.view layoutIfNeeded];
    }];
}

- (void)filteBarView:(FilterBarView *)filteBar didSelectRow:(NSInteger)row
{
    if (self.currentImageView.image == nil) {
        [[[UIAlertView alloc] initWithTitle:@"未添加图片" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:self.currentImageView.image];
    UIImage *resultImage = nil;
    if (row == 0)
    {
        GPUImageSepiaFilter *stillImageFilter = [[GPUImageSepiaFilter alloc] init];

        //法1：
//        [stillImageSource addTarget:stillImageFilter];
//        [stillImageFilter useNextFrameForImageCapture];
//        [stillImageSource processImage];
//
//        resultImage = [stillImageFilter imageFromCurrentFramebuffer];
        
        //法2：
        resultImage = [stillImageFilter imageByFilteringImage:self.currentImageView.image];
    }
    else if (row == 1) {
        
    }
    self.currentImageView.image = resultImage;
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
